//
//  XCCycleBaseBanner.swift
//  XCCycleBanner
//
//  Created by edy on 2023/7/10.
//

import UIKit

let kMultiplier = 1000

public class XCCycleBaseBanner: UIView {
    
    var timer: Timer?

    var params: XCCycleParams = XCCycleParams()

    var pageCount: Int = 0
    
    var currentIndexPath: IndexPath = IndexPath(row: 0, section: 0) {
        didSet { setCurrentIndex() }
    }

    func setCurrentIndex(){}
    
    var lastCenterIndex: Int?
    var lastIndexPathCell: UICollectionViewCell?
    
    var cellRegister: XCCycleCellRegister?
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.autoresizingMask = []
        installNotifications()
        setupSubViews()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        installNotifications()
        setupSubViews()
    }
    
    //MARK: - override
    override public func layoutSubviews() {
        super.layoutSubviews()
        if pageCount > 0 {
            scrollToIndexPath(currentIndexPath, animated: false)
        }
    }
    
    override public func removeFromSuperview() {
        stop()
        super.removeFromSuperview()
    }
    
    override public func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if newSuperview == nil {
            stop()
        }
    }
    
    deinit {
        stop()
        NotificationCenter.default.removeObserver(self)
        print("\(#function) ----------> \(self)")
    }
    
    func installNotifications() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(applicationDidEnterBackground(_:)),
            name: UIApplication.didEnterBackgroundNotification,
            object: nil
        )
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(applicationDidBecomeActive(_:)),
            name: UIApplication.didBecomeActiveNotification,
            object: nil
        )
    }
    
    func setupSubViews() {
        self.addSubview(collectionView)
    }
    
    lazy var layout: XCCycleLayout = {
        let layout = XCCycleLayout()
        layout.params = XCCycleLayoutParams()
        return layout
    }()
    
    lazy var collectionView: UICollectionView = {
        let collectionView: UICollectionView =
            UICollectionView(frame: self.bounds,
                             collectionViewLayout: self.layout)
        collectionView.backgroundColor = UIColor.clear
        collectionView.isPagingEnabled = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.autoresizingMask = [
            .flexibleWidth,
            .flexibleHeight
        ]
        return collectionView
    }()
    
    func scrollToIndexPath(
        _ indexPath: IndexPath, animated: Bool) {
        
        // Handle indexpath bounds
        if params.cycleWay == .forward,
            pageCount > 1 {
            
            if indexPath.row >= kMultiplier * pageCount - pageCount{
                currentIndexPath = IndexPath(row: (kMultiplier * pageCount / 2),
                                             section: 0)
                scrollToIndexPath(currentIndexPath, animated: false)
                return
                
            }else if indexPath.row == -1 + pageCount {
                currentIndexPath = IndexPath(row: (kMultiplier * pageCount / 2) + (pageCount - 1),
                                             section: 0)
                scrollToIndexPath(currentIndexPath, animated: false)
                return
            }
        }
        
        if params.isPagingEnabled {
            
            // reuse scrollToItem: to mask the bug of inaccurate scroll position
            var scrollPosition: UICollectionView.ScrollPosition = .centeredHorizontally
            if layout.params?.scrollDirection == .vertical {
                scrollPosition = .centeredVertically
            }
            collectionView.scrollToItem(at: indexPath,
                                        at: scrollPosition,
                                        animated: animated)
            collectionView.scrollToItem(at: indexPath,
                                        at: scrollPosition,
                                        animated: animated)
        }
    }
    
    
    
    @objc func autoScroll() {}
}


public extension XCCycleBaseBanner {
    
    func pause() {
        if let timer = self.timer {
            timer.fireDate = Date.distantFuture
        }
    }
    
    func resume() {
        timer?.fireDate = Date(timeIntervalSinceNow: params.timeInterval)
    }
    
    func start() {
        if params.isAutoPlay,
           params.timeInterval > 0,
           pageCount > 1 {
            if timer == nil {
                timer = Timer.xc_scheduledTimer(
                    withTimeInterval: params.timeInterval,
                    repeats: true,
                    block: {(timer) in
                        self.autoScroll()
                    })
                RunLoop.current.add(timer!, forMode: .common)
            }
            resume()
        }
    }
    
    func stop() {
        timer?.invalidate()
        timer = nil
    }
}


public extension XCCycleBaseBanner {
    @objc func applicationDidEnterBackground(
        _ notification: Notification) {
        pause()
    }
    
    @objc func applicationDidBecomeActive(
        _ notification: Notification) {
        // Determine if it's on screen
        guard isShowingOnWindow() != false,
            pageCount > 1 else { return }
        resume()
    }
}
